package cn.youth.datacollection.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.youth.datacollection.core.povo.Result;
import cn.youth.datacollection.core.povo.TreeDTO;
import cn.youth.datacollection.core.repository.RepositoryUtil;
import cn.youth.datacollection.entity.DiCategory;
import cn.youth.datacollection.entity.DiRespository;
import cn.youth.datacollection.entity.KRepository;
import cn.youth.datacollection.mapper.DiCategoryMapper;
import cn.youth.datacollection.mapper.DiScriptMapper;
import cn.youth.datacollection.mapper.KRepositoryMapper;
import cn.youth.datacollection.service.DiCategoryService;
import cn.youth.datacollection.util.BeanUtil;
import cn.youth.datacollection.util.SecUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.pentaho.di.repository.AbstractRepository;
import org.pentaho.di.repository.LongObjectId;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DiCategoryServiceImpl extends ServiceImpl<DiCategoryMapper, DiCategory> implements DiCategoryService {
    @Autowired
    DiCategoryMapper diCategoryMapper;
    @Autowired
    DiScriptMapper diScriptMapper;
    @Autowired
    KRepositoryMapper kRepositoryMapper;
    @Value("${spoon.url}")
    private String REPOSITORY_URL;

    @Override
    public Result<Object> delete(String dirId, String repId) throws Exception {
        Result result = new Result();
        AbstractRepository abstractRepository = RepositoryUtil.getAbstractRepository(repId);
        RepositoryDirectoryInterface directory = abstractRepository.loadRepositoryDirectoryTree().findDirectory(RepositoryUtil.getObjectId(abstractRepository, dirId));
        List<RepositoryDirectoryInterface> children = directory.getChildren();
        if (children.size() == 0) {
            abstractRepository.deleteRepositoryDirectory(directory);
            result.setCode("0000");
            result.setMessage("删除成功！");
        } else {
            result.setCode("9999");
            result.setMessage("当前目录存在下级目录或脚本，不允许删除！");
        }
        return result;
    }

    /**
     * 更新目录名称
     *
     * @param json JSON对象，包含目录的repId、dirId和新名称
     * @throws Exception 如果更新目录名称时发生异常
     */
    public void update(JSONObject json) throws Exception {
        // 获取AbstractRepository实例
        AbstractRepository abstractRepository = RepositoryUtil.getAbstractRepository(json.getString("repId"));

        // 加载仓库目录树并找到指定的目录
        RepositoryDirectoryInterface directory = abstractRepository.loadRepositoryDirectoryTree().findDirectory(RepositoryUtil.getObjectId(abstractRepository, json.getLong("dirId")));

        // 使用新名称重命名目录
        abstractRepository.renameRepositoryDirectory(new LongObjectId(json.getLong("dirId")), directory.getParent(), json.getString("name"));
    }

    public List<TreeDTO<String>> findDiCateryByRep(String repId) throws Exception {
        List<TreeDTO<String>> treeList = new ArrayList<>();
        AbstractRepository abstractRepository = RepositoryUtil.getAbstractRepository(repId);
        // 获取当前的路径信息
        RepositoryDirectoryInterface rdi = abstractRepository.loadRepositoryDirectoryTree().findDirectory("");
        List<TreeDTO<String>> subdirectories = RepositoryUtil.getSubdirectories(new ArrayList<>(), rdi);
        /*subdirectories.forEach(dt -> {
            try {
                treeList.addAll(RepositoryUtil.getSubdirectories(abstractRepository.loadRepositoryDirectoryTree().findDirectory(dt.getExtra())));
            } catch (KettleException e) {
                e.printStackTrace();
            }
        });*/
        treeList.addAll(subdirectories);
        //List<DiCategory> all = diCategoryMapper.findByRepIdOrderByCode(repId);
        return subdirectories;
    }

    /**
     * 根据id查找仓库
     *
     * @param id 仓库id
     * @return 返回DiRespository对象
     */
    public DiRespository findRepositoryById(String id) {
        KRepository kRepository = kRepositoryMapper.selectById(id);
        DiRespository repDto = null;
        if (kRepository != null) {
            repDto = BeanUtil.copyProperties(kRepository, DiRespository.class);
        }
        repDto.setUrl(REPOSITORY_URL);
        return repDto;
    }


    /**
     * 添加目录
     *
     * @param json 请求的JSON对象
     * @return 添加结果
     * @throws Exception 异常
     */
    public Result add(JSONObject json) throws Exception {
        Result result = new Result();
        AbstractRepository abstractRepository = RepositoryUtil.getAbstractRepository(json.getString("repId"));
        RepositoryDirectoryInterface directory;
        if (json.containsKey("dirId") && !StrUtil.isEmpty(json.getString("dirId"))) {
            directory = abstractRepository.loadRepositoryDirectoryTree().findDirectory(RepositoryUtil.getObjectId(abstractRepository, json.get("dirId")));
        } else {
            directory = abstractRepository.getUserHomeDirectory();
        }
        RepositoryDirectoryInterface directoryChild = directory.findChild(json.getString("name"));
        if (directoryChild == null) {
            abstractRepository.createRepositoryDirectory(directory, json.getString("name"));
            result.setCode("0000");
            result.setMessage("创建成功！");
        } else {
            result.setCode("9999");
            result.setMessage("目录已存在！");
        }

        return result;
    }


    /**
         * 根据指定的id、类型和脚本id获取加密后的DiRespository对象
         *
         * @param id       DiRespository对象的id
         * @param type     类型，1表示传输脚本，2表示作业
         * @param scriptId 脚本id
         * @return 加密后的DiRespository对象
         */
        @Override
        public DiRespository getEncryptionUrl(String id, int type, String scriptId) {
            // 通过id查询KRepository对象
            KRepository kRepository = kRepositoryMapper.selectById(id);

            // 创建DiRespository对象
            DiRespository repDto = null;

            // 如果KRepository对象不为空，则将其属性复制到repDto对象中
            if (kRepository != null) {
                repDto = BeanUtil.copyProperties(kRepository, DiRespository.class);
            }

            // 构建加密URL
            String encryptionUrl = "rep=" + repDto.getRepName() + "&user=" + repDto.getRepUsername() + "&pass=" + repDto.getRepPassword();

            // 根据类型添加脚本id
            if (type == 1) {
                encryptionUrl = encryptionUrl + "&trans=" + scriptId;
            } else {
                encryptionUrl = encryptionUrl + "&job=" + scriptId;
            }

            // 清空密码和用户名
            repDto.setRepPassword("");
            repDto.setRepUsername("");

            // 加密URL
            encryptionUrl = SecUtil.encrypt(encryptionUrl.trim());

            // 设置最终的URL地址
            repDto.setUrl(REPOSITORY_URL + "?respoon=" + encryptionUrl);

            // 返回加密后的DiRespository对象
            return repDto;
        }
}
